package com.github.webshell.service;

import com.github.webshell.handler.WebSocketWsHandler;
import com.github.webshell.config.Const;
import org.tio.server.ServerTioConfig;
import org.tio.utils.Threads;
import org.tio.websocket.server.WsServerConfig;
import org.tio.websocket.server.WsServerStarter;

public class WebSocketServerStarter {

    private static ServerTioConfig wsServerTioConfig;

    // 开放外部获取 serverTioConfig
    public static ServerTioConfig getServerTioConfig() {
        return wsServerTioConfig;
    }

    public void start() throws Exception {
        // 配置WebSocket 启动端口
        WsServerConfig config = new WsServerConfig(Const.WEB_SOCKET_PORT);
        // 配置消息处理Handler
        WsServerStarter wsServerStarter = new WsServerStarter(config, new WebSocketWsHandler(), Threads.getTioExecutor(), Threads.getGroupExecutor());
        wsServerTioConfig = wsServerStarter.getServerTioConfig();
        // 配置服务启动名字，默认是 Tio-WebSocket-Server
        wsServerTioConfig.setName(Const.WEB_SOCKET_NAME);
        // 设置一分钟没有心跳就主动断开连接
        wsServerTioConfig.setHeartbeatTimeout(60000);
        // WebSocket 服务启动
        wsServerStarter.start();
    }
}
